package stdio.costa.imoca.api;

import java.util.ArrayList;
import java.util.List;

import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import stdio.costa.imoca.notification.email.EmailRecipient;
import stdio.costa.imoca.notification.email.EmailSender;

@Path("/email")
@Component
@Scope("request")
public class EmailResource {

	@Autowired
	private EmailSender emailSender;

	@Path("/send")
	@POST
	@Produces({ "application/json;qs=1", "application/xml;qs=.5" })
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@Transactional
	public void sendEmail(@QueryParam("access_token") String accessTokenCode,
			@QueryParam("to") String toStr,
			@DefaultValue("") @QueryParam("bcc") String bccStr,
			@DefaultValue("") @QueryParam("cc") String ccStr,
			@QueryParam("title") String title,
			@QueryParam("content") String content) throws Exception {

		List<EmailRecipient> recipientList = new ArrayList<EmailRecipient>();
		
		recipientList.addAll(convert(toStr, RecipientType.TO));
		
		recipientList.addAll(convert(bccStr, RecipientType.BCC));
		
		recipientList.addAll(convert(ccStr, RecipientType.CC));
		
		emailSender.sendEmail(recipientList, title, content);

	}

	private List<EmailRecipient> convert(String str, Message.RecipientType type) throws AddressException {
		
		if(StringUtils.isEmpty(str)){
			return new ArrayList<EmailRecipient>();
		}
		
		String[] array = StringUtils.split(str, ",");
		if (array == null || array.length == 0) {
			return new ArrayList<EmailRecipient>();
		}
		
		List<EmailRecipient> list = new ArrayList<EmailRecipient>();
		
		for (String arr : array) {
			list.add(new EmailRecipient(new InternetAddress(arr), type));
		}

		return list;
	}

}